﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Site3AI.Models;
using WxServices.Models;

namespace WxServices.Controllers
{
    public class WeiXinSvcController : ApiController
    {
        static Lazy<WxServices.Services.WxService> _svc = new Lazy<WxServices.Services.WxService>();
        WxServices.Services.WxService Service
        {
            get
            {
                return _svc.Value;
            }
        }
        SiteDbEntities DB
        {
            get
            {
                return Service.DB;
            }
        }

        protected override void Dispose(bool disposing)
        {
            //if (_svc.IsValueCreated) _svc.Value.Dispose();
            base.Dispose(disposing);
        }

        //public System.Net.Http.HttpResponseMessage Get(string signature, string timestamp, string nonce, string echostr)
        public string Get(string signature, string timestamp, string nonce, string echostr)
        {
            #region Log weixinecho
            DB.WeiXinEchoLogs.Add(new WeiXinEchoLog()
            {
                Id = Guid.NewGuid(),
                Timemark = DateTime.Now,
                Signature = signature,
                Timestamp = timestamp,
                Nonce = nonce,
                Echostr = echostr
            });
            DB.SaveChanges();
            #endregion

            var errorstr = "signature not match";

            var b = Service.VerifyWxSignature(signature, timestamp, nonce);
            var r = b ? echostr : errorstr;
            return r;
            //return new System.Net.Http.HttpResponseMessage()
            //{
            //    Content = new System.Net.Http.StringContent(r, System.Text.Encoding.UTF8, "text/plain")
            //};

        }

        public string Post([FromBody]string rawbody, [FromUri]string signature, [FromUri]string timestamp, [FromUri]string nonce)
        {
            var b = Service.VerifyWxSignature(signature, timestamp, nonce);
            if (!b) return null;
            WxMessageFull rawmsg = Service.ParseWxMessage(rawbody);
            #region log msg to db
            
            DB.WeiXinRawMessages.Add(new WeiXinRawMessage() { Id = Guid.NewGuid(), RawMsg = rawbody, Timemark = DateTime.Now });
            DB.SaveChanges();


            if (DB.WeiXinFullMessages.Find(rawmsg.MsgId) != null) return null;//TODO:return xml --skip

            var fm = new WeiXinFullMessage()
            {
                MsgId = (rawmsg.MsgId == 0 ? -DateTime.UtcNow.Ticks : rawmsg.MsgId),
                Content = rawmsg.Content,
                CreateTime = rawmsg.CreateTime,
                Description = rawmsg.Description,
                Format = rawmsg.Format,
                FromUserName = rawmsg.FromUserName,
                ToUserName = rawmsg.ToUserName,
                Label = rawmsg.Label,
                Location_X = rawmsg.Location_X,
                Location_Y = rawmsg.Location_Y,
                MediaId = rawmsg.MediaId,
                MsgType = rawmsg.MsgType,
                PicUrl = rawmsg.PicUrl,
                Scale = rawmsg.Scale,
                ThumbMediaId = rawmsg.ThumbMediaId,
                Title = rawmsg.Title,
                Url = rawmsg.Url,
                Event = rawmsg.Event,
                EventKey = rawmsg.EventKey,
                Ticket = rawmsg.Ticket,
                Latitude = rawmsg.Latitude,
                Longitude = rawmsg.Longitude,
                Precision = rawmsg.Precision
            };
            DB.WeiXinFullMessages.Add(fm);
            DB.SaveChanges();
            #endregion

            var resultContentPatt = DB.SystemSettings.Find("TestWxReplyMsgTemplate").Setting;
            var resultContent = string.Format(resultContentPatt, rawmsg.FromUserName);

            var resultobj= new WxResultText()
            {
                Content = resultContent,
                CreateTime = Service.ToPosixTime(DateTime.UtcNow).ToString(),
                FromUserName = rawmsg.ToUserName,
                ToUserName = rawmsg.FromUserName
            };
            var resultXmlString=Service.ToWxResultXml<WxResultBase>(resultobj);
            System.Diagnostics.Trace.WriteLine(resultXmlString);
            return resultXmlString;

        }
    }
}